<template>
  <div>
		<!-- fileList: {{ fileList }} -->
    <a-upload
		  name="image"
      :action="action"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :file-list="fileList"
      list-type="picture-card"
      @change="handleChange"
      @preview="handlePreview"
    >
      <div v-if="fileList.length < limit && !disabled">
        <a-icon type="plus"/>
        <div class="ant-upload-text">
          新的上传图片
        </div>
      </div>
    </a-upload>
    <a-modal style="height:1000px" :visible="previewVisible" :footer="null" @cancel="handlePreviewCancel">
      <img alt="example" style="width: 100%;height:100%;object-fit:cover" :src="previewImage"/>
    </a-modal>
  </div>
</template>
<script>
export default {
  name: 'UploadImageMore',
	model: { prop: 'modelValue', event: 'update:modelValue'},
  // -----------------------修改apiTest-----------------------------
  props: {
    action: { type: String, default: '/api/sysFileInfo/upload' },
    limit: { type: Number, default: 8 },
    disabled: { type: Boolean, default: false },
  },
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: ''
    }
  },
  // 首先将值转为数组
  watch: {
    'modelValue':{
      handler(newValue){
				console.log('newValue', newValue)
				this.fileList = []
				if (newValue) {				
					this.fileList = this.uploadList = Array.isArray(newValue) ? newValue : this.modelValue.split(",").map((item) => ({ url: item }));
				} else {
					this.fileList = []
				}
      },
      immediate: true,  //是否在初始的时候监听
    }
	},
  methods: {
		// 对象转成指定字符串分隔
		listToString() {
			return this.uploadList.map(item=>item.url||'').join(',')
		},
    beforeUpload(file) {
      const isJpgOrPng = file.type==='image/jpeg' || file.type==='image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片类型文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!isLt2M) {
        this.$message.error('文件大小必须小于20MB!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(event) {
      // TODO 看了源码,懂了一点.不重写上传方法也没问题.当上传成功时,可以从event.file.response 中 获取到服务器返回内容
      let {file, fileList} = event

      this.fileList = fileList
      // 如果在上传前判断格式或大小不符合，将不会进行自动上传。这处的状态为undefined
      if (file.status === undefined) {
        fileList.pop()
      }

      // 只有当成功上传或删除时,才调用父级的变动方法
      if (file.status === 'done') {
        // 由于file和FileList中的对象不是同一个,所以需要找到受控的对象,再加添属性
        let findFile = fileList.find(f => f.uid == file.uid)
        // 服务端响应内容
        let response = findFile.response
        findFile.fileID = response.data
      }
    },
    handlePreview (file) {
      this.previewImage = file.url || file.preview || `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${file.fileID}` 
      this.previewVisible = true
    },
    handlePreviewCancel() {
      this.previewVisible = false
      this.previewImage = ''
    },
    handleClear() {
      this.fileList = []
    }
  }
}
</script>